﻿using System;
using System.Text;
using System.Web.Mvc;
using System.Linq;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Kobets.Automation.Chimera.Common;
using Kobets.Automation.Chimera.Orchestrator.Models;
using Kobets.Automation.Chimera.Orchestrator.Shared;

namespace Kobets.Automation.Chimera.Orchestrator.Controllers
{
    public class ResultsController : Controller
    {
        private readonly TestResultsDBEntities testResults = new TestResultsDBEntities();

        public ActionResult Index(string id)
        {
            if (!String.IsNullOrWhiteSpace(id))
            {
                var filter = "{ field: \"TestID\", operator: \"eq\", value: " + id + " }";

                if (id.Contains("a"))
                {
                    filter = "[{ logic: \"or\", filters: [";
                    filter += id.Split('a').Aggregate("", (current, tid) => current + new StringBuilder("{ field: \"TestID\", operator: \"eq\", value: " + tid + " }, "));
                    filter.Remove(filter.Length - 2);
                    filter += "]}]";
                }

                ViewBag.TestID = filter;
            }

            return View();
        }

        public ActionResult GetFirstLevelData([DataSourceRequest]DataSourceRequest request)
        {
            var tests = testResults.Tests.ToList().Distinct(new TestComparer()).Select(t => new ProductModel { ProductName = t.ProductName.Trim() }).ToDataSourceResult(request);
            return Json(tests);
        }
        
        public ActionResult GetSecondLevelData(string productName, [DataSourceRequest]DataSourceRequest request)
        {
            return Json(testResults.Tests.ToList().Where(p => p.ProductName == productName.Trim()).Select(t => new VersionModel { ProductName = productName.Trim(), Version =  t.Version.Trim().Replace(".", "_") }).Distinct(new VersionModelComparer()).ToList().ToDataSourceResult(request));
        }

        public ActionResult GetData(string productName, string version, [DataSourceRequest]DataSourceRequest request)
        {
            return Json(testResults.Tests.ToList().Where(p => p.Version == version.Trim().Replace("_", ".") && p.ProductName == productName.Trim()).ToDataSourceResult(request));
        }

        public ActionResult GetTestData([DataSourceRequest]DataSourceRequest request)
        {
            return Json(testResults.Tests.ToList().ToDataSourceResult(request));
        }

        public ActionResult GetDetailedData([DataSourceRequest]DataSourceRequest request, int testId)
        {
            var testDetails = testResults.TestResults.Where(tid => tid.TestID == testId);
            var result = testDetails.ToDataSourceResult(request);
            return Json(result);
        }
    }
}